package com.taoym.voucher.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taoym.voucher.admin.domain.XcxImageInfo;
import com.taoym.voucher.admin.entity.dto.XcxAddImageDTO;
import com.taoym.voucher.admin.entity.vo.XcxGetImageVO;
import com.taoym.voucher.admin.mapper.XcxImageInfoMapper;
import com.taoym.voucher.admin.service.XcxImageService;
import com.taoym.voucher.common.enums.ImageInfoTypeEnum;
import com.taoym.voucher.common.enums.ImageSuffixEnum;
import com.taoym.voucher.common.response.ResponseStatusCode;
import com.taoym.voucher.common.utils.ExceptionCore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @coder taoym
 * @datetime 2021/9/3 9:17
 * @desc
 */
@Service
@Slf4j
public class XcxImageServiceImpl implements XcxImageService {

    @Resource
    private XcxImageInfoMapper xcxImageInfoMapper;
    @Value(value = "${file.upload}")
    private String filePath;
    @Value(value = "${nginx.path}")
    private String nginxAddress;


    @Override
    public List<XcxGetImageVO> listImages(Integer type) {
        List<XcxImageInfo> images = xcxImageInfoMapper.selectList(new QueryWrapper<XcxImageInfo>().eq("type", type));
        if (CollectionUtils.isEmpty(images)) {
            return null;
        }
        List<XcxGetImageVO> xcxGetImageVOS = new ArrayList<>(images.size());
        images.forEach(e -> {
            XcxGetImageVO xcxGetImageVO = new XcxGetImageVO();
            xcxGetImageVO.setUrl(e.getUrl());
            xcxGetImageVO.setUid(e.getUid());
            xcxGetImageVO.setId(e.getId());
            xcxGetImageVO.setType(ImageInfoTypeEnum.getMsg(e.getType()));
            xcxGetImageVOS.add(xcxGetImageVO);
        });

        return xcxGetImageVOS;
    }

    @Override
    public Integer addImage(XcxAddImageDTO data) {
        String url = upload(data.getFile());
        XcxImageInfo xcxImageInfo = new XcxImageInfo();
        xcxImageInfo.setUid("000000");
        xcxImageInfo.setUrl(url);
        xcxImageInfo.setType(data.getType());
        return xcxImageInfoMapper.insert(xcxImageInfo);
    }

    @Override
    public Integer deleteImage(Integer id, String url) {
        Boolean isDeleted = delete(url);
        if (isDeleted) {
            return xcxImageInfoMapper.deleteById(id);
        }
        return 0;
    }

    private String upload(MultipartFile files) {
        String fileUrl = generatorFileUrl(files);
        // 取处理后的文件名称
        String fileName = fileUrl.replace(nginxAddress, "");

        Path path = Paths.get(filePath + fileName);
        byte[] bytes;
        try {
            bytes = files.getBytes();
            Files.write(path, bytes);
        } catch (IOException e) {
            throw new ExceptionCore(ResponseStatusCode.FILE_UPLOAD_FAIL);
        }
        return nginxAddress + fileName;
    }


    private Boolean delete(String url) {
        String fileName = url.replace(nginxAddress, "");
        try {
            Path path = Paths.get(filePath + fileName);
            Files.delete(path);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("file delete is fail {}", url);
            return false;
        }
        return true;
    }

    private String generatorFileUrl(MultipartFile files) {
        if (files == null) {
            throw new ExceptionCore(ResponseStatusCode.FILE_UPLOAD_FAIL);
        }
        // 获取文件名称
        String fileName = files.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (!ImageSuffixEnum.getImageSuffix(suffixName)) {
            throw new ExceptionCore(ResponseStatusCode.FILE_UPLOAD_FAIL);
        }
        //重新生成文件名
        fileName = UUID.randomUUID() + suffixName;
        // 返回的是图片的访问地址
        return nginxAddress + fileName;
    }
}
